
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Java,设计模式,Design Pattern," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>Builder模式——设计模式 [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        Builder模式——设计模式
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Design-Pattern/" rel="tag">Design Pattern</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java/" rel="tag">Java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">设计模式</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 10 分钟</span>
    </header>

    <div class="post-content">
      <h3 id="Builder模式"><a href="#Builder模式" class="headerlink" title="Builder模式"></a>Builder模式</h3><h4 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h4><p>构建对象时，如果碰到类有很多参数——其中很多参数类型相同而且很多参数可以为空时，推荐Builder模式来完成。当参数数量不多、类型不同而且都是必须出现时，通过增加代码实现Builder往往无法体现它的优势。在这种情况下，理想的方法是调用传统的构造函数。再者，如果不需要保持不变，那么就使用无参构造函数调用相应的set方法吧。</p>
<h4 id="普通方式，通过构造方法创建实例"><a href="#普通方式，通过构造方法创建实例" class="headerlink" title="普通方式，通过构造方法创建实例"></a>普通方式，通过构造方法创建实例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.ubuntuvim.pattern.builder;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Builder 模式 创建类实例方式:&lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 1. 普通方式，通过构造方法创建 &lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 2. JavaBean方式创建&lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 3. Builder 模式</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> ubuntuvim</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Car</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 必需属性</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String carBody;<span class="comment">//车身</span></span><br><span class="line">    <span class="keyword">private</span> String tyre;<span class="comment">//轮胎</span></span><br><span class="line">    <span class="keyword">private</span> String engine;<span class="comment">//发动机</span></span><br><span class="line">    <span class="keyword">private</span> String aimingCircle;<span class="comment">//方向盘</span></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 可选属性</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String decoration;<span class="comment">//车内装饰品</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 必备属性创建实例</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> carBody</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> tyre</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> engine</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> aimingCircle</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Car</span><span class="params">(String carBody, String tyre, String engine, String aimingCircle)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>();</span><br><span class="line">        <span class="keyword">this</span>.carBody = carBody;</span><br><span class="line">        <span class="keyword">this</span>.tyre = tyre;</span><br><span class="line">        <span class="keyword">this</span>.engine = engine;</span><br><span class="line">        <span class="keyword">this</span>.aimingCircle = aimingCircle;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 增加可选属性创建实例</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> carBody</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> tyre</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> engine</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> aimingCircle</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Car</span><span class="params">(String carBody, String tyre, String engine, String aimingCircle, String decoration)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>();</span><br><span class="line">        <span class="keyword">this</span>.carBody = carBody;</span><br><span class="line">        <span class="keyword">this</span>.tyre = tyre;</span><br><span class="line">        <span class="keyword">this</span>.engine = engine;</span><br><span class="line">        <span class="keyword">this</span>.aimingCircle = aimingCircle;</span><br><span class="line">        <span class="keyword">this</span>.decoration = decoration;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Car [carBody=&quot;</span> + carBody + <span class="string">&quot;, tyre=&quot;</span> + tyre + <span class="string">&quot;, engine=&quot;</span> + engine + <span class="string">&quot;, aimingCircle=&quot;</span> + aimingCircle</span><br><span class="line">                + <span class="string">&quot;, decoration=&quot;</span> + decoration + <span class="string">&quot;]&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这是最常见的、最普通的方式——通过构造方法传递属性，并创建实例。</p>
<p>简单使用main方法模拟调用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.ubuntuvim.pattern.builder;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 通过不同方式获取实例</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 1. 普通方式，通过构造方法初始化属性，弊端：参数多，而且更重要的是参数的次序不能错</span></span><br><span class="line">        Car c = <span class="keyword">new</span> Car(<span class="string">&quot;carBody&quot;</span>, <span class="string">&quot;tyre&quot;</span>, <span class="string">&quot;engine&quot;</span>, <span class="string">&quot;aimingCircle&quot;</span>);</span><br><span class="line">        System.out.println(c);</span><br><span class="line">       </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这种方式简单，但是参数多的情况传参麻烦，并且参数次序不能错，否则得到的实例不是自己想要的。</p>
<h4 id="JavaBean方式创建"><a href="#JavaBean方式创建" class="headerlink" title="JavaBean方式创建"></a>JavaBean方式创建</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.ubuntuvim.pattern.builder;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Builder 模式 创建类实例方式:&lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 1. 普通方式，通过构造方法创建 &lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 2. JavaBean方式创建&lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 3. Builder 模式</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> ubuntuvim</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Car2</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 必需属性</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String carBody;<span class="comment">// 车身</span></span><br><span class="line">    <span class="keyword">private</span> String tyre;<span class="comment">// 轮胎</span></span><br><span class="line">    <span class="keyword">private</span> String engine;<span class="comment">// 发动机</span></span><br><span class="line">    <span class="keyword">private</span> String aimingCircle;<span class="comment">// 方向盘</span></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 可选属性</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String decoration;<span class="comment">// 车内装饰品</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCarBody</span><span class="params">(String carBody)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.carBody = carBody;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setTyre</span><span class="params">(String tyre)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.tyre = tyre;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setEngine</span><span class="params">(String engine)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.engine = engine;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAimingCircle</span><span class="params">(String aimingCircle)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.aimingCircle = aimingCircle;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setDecoration</span><span class="params">(String decoration)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.decoration = decoration;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Car2 [carBody=&quot;</span> + carBody + <span class="string">&quot;, tyre=&quot;</span> + tyre + <span class="string">&quot;, engine=&quot;</span> + engine + <span class="string">&quot;, aimingCircle=&quot;</span> + aimingCircle</span><br><span class="line">                + <span class="string">&quot;, decoration=&quot;</span> + decoration + <span class="string">&quot;]&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.ubuntuvim.pattern.builder;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 通过不同方式获取实例</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 1. 普通方式，通过构造方法初始化属性，弊端：参数多，而且更重要的是参数的次序不能错</span></span><br><span class="line">        Car c = <span class="keyword">new</span> Car(<span class="string">&quot;carBody&quot;</span>, <span class="string">&quot;tyre&quot;</span>, <span class="string">&quot;engine&quot;</span>, <span class="string">&quot;aimingCircle&quot;</span>);</span><br><span class="line">        System.out.println(c);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 2. javabean方式，通过setter方法初始化属性</span></span><br><span class="line">        Car2 c2 = <span class="keyword">new</span> Car2();</span><br><span class="line">        c2.setCarBody(<span class="string">&quot;carBody2&quot;</span>);</span><br><span class="line">        c2.setTyre(<span class="string">&quot;tyre2&quot;</span>);</span><br><span class="line">        c2.setEngine(<span class="string">&quot;engine2&quot;</span>);</span><br><span class="line">        c2.setAimingCircle(<span class="string">&quot;aimingCircle2&quot;</span>);</span><br><span class="line">        System.out.println(c2);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>提供无参的构造函数，暴露一些公共的方法让用户自己去设置对象属性，这种方法较之第一种似乎增强了灵活度，用户可以根据自己的需要随意去设置属性。但是这种方法自身存在严重的缺点：</p>
<ol>
<li>因为构造过程被分到了几个调用中，在构造中 JavaBean 可能处于不一致的状态。类无法仅仅通过判断构造器参数的有效性来保证一致性。</li>
<li>参数无法校验，本例子中<code>carBody</code>、<code>tyre</code>、<code>engine</code>、<code>aimingCircle</code>这几个属性是必须的。Javabean的方式无法校验。</li>
</ol>
<h4 id="Builder模式-1"><a href="#Builder模式-1" class="headerlink" title="Builder模式"></a>Builder模式</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.ubuntuvim.pattern.builder;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Builder 模式 创建类实例方式:&lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 1. 普通方式，通过构造方法创建 &lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 2. JavaBean方式创建&lt;br&gt;</span></span><br><span class="line"><span class="comment"> * 3. Builder 模式</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> ubuntuvim</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Car3</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 必需属性</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String carBody;<span class="comment">// 车身</span></span><br><span class="line">    <span class="keyword">private</span> String tyre;<span class="comment">// 轮胎</span></span><br><span class="line">    <span class="keyword">private</span> String engine;<span class="comment">// 发动机</span></span><br><span class="line">    <span class="keyword">private</span> String aimingCircle;<span class="comment">// 方向盘</span></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 可选属性</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String decoration;<span class="comment">// 车内装饰品</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//  public void setCarBody(String carBody) &#123;</span></span><br><span class="line"><span class="comment">//      this.carBody = carBody;</span></span><br><span class="line"><span class="comment">//  &#125;</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//  public void setTyre(String tyre) &#123;</span></span><br><span class="line"><span class="comment">//      this.tyre = tyre;</span></span><br><span class="line"><span class="comment">//  &#125;</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//  public void setEngine(String engine) &#123;</span></span><br><span class="line"><span class="comment">//      this.engine = engine;</span></span><br><span class="line"><span class="comment">//  &#125;</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//  public void setAimingCircle(String aimingCircle) &#123;</span></span><br><span class="line"><span class="comment">//      this.aimingCircle = aimingCircle;</span></span><br><span class="line"><span class="comment">//  &#125;</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//  public void setDecoration(String decoration) &#123;</span></span><br><span class="line"><span class="comment">//      this.decoration = decoration;</span></span><br><span class="line"><span class="comment">//  &#125;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 必须的方法否则后面的`build()`方法无法把属性传递进来，&lt;br&gt;</span></span><br><span class="line"><span class="comment">     * 汽车指定某个制造商才能制造汽车，</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> builder</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Car3</span><span class="params">(Builder builder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.aimingCircle = builder.aimingCircle;</span><br><span class="line">        <span class="keyword">this</span>.carBody = builder.carBody;</span><br><span class="line">        <span class="keyword">this</span>.decoration = builder.decoration;</span><br><span class="line">        <span class="keyword">this</span>.engine = builder.engine;</span><br><span class="line">        <span class="keyword">this</span>.tyre = builder.tyre;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 汽车不会自己生产自己，通常是汽车制造商Builder生产机车，</span></span><br><span class="line"><span class="comment">     * 汽车制造商要制造汽车，它必须拿到汽车一样的属性。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Builder</span> </span>&#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 必需属性</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">private</span> String carBody;<span class="comment">// 车身</span></span><br><span class="line">        <span class="keyword">private</span> String tyre;<span class="comment">// 轮胎</span></span><br><span class="line">        <span class="keyword">private</span> String engine;<span class="comment">// 发动机</span></span><br><span class="line">        <span class="keyword">private</span> String aimingCircle;<span class="comment">// 方向盘</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 可选属性</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">private</span> String decoration;<span class="comment">// 车内装饰品</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 制造商默认生产的汽车</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">Builder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 为了能够链式调用，每个setter方法都返回this</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Builder <span class="title">setCarBody</span><span class="params">(String carBody)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.carBody = carBody;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> Builder <span class="title">setTyre</span><span class="params">(String tyre)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.tyre = tyre;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> Builder <span class="title">setEngine</span><span class="params">(String engine)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.engine = engine;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> Builder <span class="title">setAimingCircle</span><span class="params">(String aimingCircle)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.aimingCircle = aimingCircle;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> Builder <span class="title">setDecoration</span><span class="params">(String decoration)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.decoration = decoration;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 制造商返回制造出来的汽车</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">         * <span class="doctag">@throws</span> Exception </span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Car3 <span class="title">build</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.carBody == <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">&quot;carBody不允许为空。&quot;</span>);</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.aimingCircle == <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">&quot;aimingCircle不允许为空。&quot;</span>);</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.tyre == <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">&quot;tyre不允许为空。&quot;</span>);</span><br><span class="line">            <span class="comment">// this就是制造出来的汽车，默认情况下都是宝马</span></span><br><span class="line">            <span class="comment">// 可以通过Builder提供的setter方法改变汽车的属性</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Car3(<span class="keyword">this</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Car3 [carBody=&quot;</span> + carBody + <span class="string">&quot;, tyre=&quot;</span> + tyre + <span class="string">&quot;, engine=&quot;</span> + engine + <span class="string">&quot;, aimingCircle=&quot;</span> + aimingCircle</span><br><span class="line">                + <span class="string">&quot;, decoration=&quot;</span> + decoration + <span class="string">&quot;]&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.ubuntuvim.pattern.builder;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 通过不同方式获取实例</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 1. 普通方式，通过构造方法初始化属性，弊端：参数多，而且更重要的是参数的次序不能错</span></span><br><span class="line">        Car c = <span class="keyword">new</span> Car(<span class="string">&quot;carBody&quot;</span>, <span class="string">&quot;tyre&quot;</span>, <span class="string">&quot;engine&quot;</span>, <span class="string">&quot;aimingCircle&quot;</span>);</span><br><span class="line">        System.out.println(c);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 2. javabean方式，通过setter方法初始化属性</span></span><br><span class="line">        Car2 c2 = <span class="keyword">new</span> Car2();</span><br><span class="line">        c2.setCarBody(<span class="string">&quot;carBody2&quot;</span>);</span><br><span class="line">        c2.setTyre(<span class="string">&quot;tyre2&quot;</span>);</span><br><span class="line">        c2.setEngine(<span class="string">&quot;engine2&quot;</span>);</span><br><span class="line">        c2.setAimingCircle(<span class="string">&quot;aimingCircle2&quot;</span>);</span><br><span class="line">        System.out.println(c2);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 3. Builder模式，设置汽车必须属性</span></span><br><span class="line">        Car3 c32 = <span class="keyword">new</span> Car3.Builder()</span><br><span class="line">                .setAimingCircle(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">                .setCarBody(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">                .setEngine(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">                .setTyre(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">                .build();</span><br><span class="line">        System.out.println(c32);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3. Builder模式，设置汽车必须属性+可选属性</span></span><br><span class="line">        Car3 c33 = <span class="keyword">new</span> Car3.Builder()</span><br><span class="line">                .setAimingCircle(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">                .setCarBody(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">                .setEngine(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">                .setTyre(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">                .setDecoration(<span class="string">&quot;可选属性：高级音响&quot;</span>)</span><br><span class="line">                .build();</span><br><span class="line">        System.out.println(c33);</span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3. Builder模式，没有设置任何属性，属性校验不通过</span></span><br><span class="line">        Car3 c3 = <span class="keyword">new</span> Car3.Builder().build();</span><br><span class="line">        System.out.println(c3);</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>首先参数的设置包含了javabean的特点，不需要关注参数的次序并且可以链式设置，代码更优雅；其次，可以校验一些必须的参数。</p>
<p>以上就是Builder模式。</p>

    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/Ember-Teach%E6%95%99%E7%A8%8B%E7%9B%AE%E5%BD%95/" rel="next" title="Ember-Teach教程目录">
          Ember-Teach教程目录
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/NodeJS/express%E8%8E%B7%E5%8F%96%E5%8F%82%E6%95%B0%E7%9A%84%E6%96%B9%E6%B3%95/" rel="prev" title="express获取参数的方法">
            express获取参数的方法
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Builder%E6%A8%A1%E5%BC%8F"><span class="toc-text">Builder模式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%99%AE%E9%80%9A%E6%96%B9%E5%BC%8F%EF%BC%8C%E9%80%9A%E8%BF%87%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BE%8B"><span class="toc-text">普通方式，通过构造方法创建实例</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#JavaBean%E6%96%B9%E5%BC%8F%E5%88%9B%E5%BB%BA"><span class="toc-text">JavaBean方式创建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Builder%E6%A8%A1%E5%BC%8F-1"><span class="toc-text">Builder模式</span></a></li></ol></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: 'Builder模式——设计模式', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
